package com.sephiron.clocksynchronizer;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.CheckBox;
import android.widget.NumberPicker;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Period;

public class IntervalPickerFragment extends DialogFragment {
    public static final String EXTRA_DATETIME_CCTV = "com.sephiron.clocksynchronizer.datetime.cctv";
    public static final String EXTRA_DATETIME_REAL = "com.sephiron.clocksynchronizer.datetime.real";
    public static final String TAG = "IntervalPickerFragment";

    private NumberPicker dayPicker;
    private NumberPicker hourPicker;
    private NumberPicker minutePicker;
    private NumberPicker secondPicker;
    private CheckBox checkBox;

    private DateTime mCctv;
    private DateTime mReal;

    private int days=0;
    private int hours=0;
    private int minutes=0;
    private int seconds=0;

    public static IntervalPickerFragment newInstance(DateTime cctv, DateTime real) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_DATETIME_CCTV, cctv);
        args.putSerializable(EXTRA_DATETIME_REAL, real);

        IntervalPickerFragment fragment = new IntervalPickerFragment();
        fragment.setArguments(args);

        return fragment;
    }

    private void sendResult(int resultCode) {
        if (getTargetFragment() == null) {
            return;
        }

        mCctv = checkBox.isChecked() ?
                mReal.plusDays(days).plusHours(hours).plusMinutes(minutes).plusSeconds(seconds) :
                mReal.minusDays(days).minusHours(hours).minusMinutes(minutes).minusSeconds(seconds) ;

        Intent i = new Intent();
        i.putExtra(EXTRA_DATETIME_CCTV, mCctv); // return only cctv in DateTime
        getTargetFragment().onActivityResult(getTargetRequestCode(),
                resultCode, i);
    }

    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public Dialog onCreateDialog(Bundle savedInstanceState) {
//        setRetainInstance(true);

        mCctv = new DateTime(getArguments().getSerializable(EXTRA_DATETIME_CCTV));
        mReal = new DateTime(getArguments().getSerializable(EXTRA_DATETIME_REAL));
        View v = getActivity().getLayoutInflater().inflate(
                R.layout.dialog_set_interval, null);
        checkBox = (CheckBox) v.findViewById(R.id.checkBox);

        Period p;
        Days daysInDays;
        if (mCctv.getMillis() > mReal.getMillis()) { // if cctv is faster
            checkBox.setChecked(true);
            daysInDays = Days.daysBetween(mReal, mCctv);
            p = new Period(mReal, mCctv);
        } else {
            daysInDays = Days.daysBetween(mCctv, mReal);
            p = new Period(mCctv, mReal);
        }

        days = daysInDays.getDays();
        hours = p.getHours();
        minutes = p.getMinutes();
        seconds = p.getSeconds();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            dayPicker = (NumberPicker) v.findViewById(R.id.dialogIntervalDayPicker);
            hourPicker = (NumberPicker) v.findViewById(R.id.dialogIntervalHourPicker);
            minutePicker = (NumberPicker) v.findViewById(R.id.dialogIntervalMinutePicker);
            secondPicker = (NumberPicker) v.findViewById(R.id.dialogIntervalSecPicker);

            dayPicker.setMaxValue(99999);
            dayPicker.setMinValue(0);
            hourPicker.setMaxValue(23);
            hourPicker.setMinValue(0);
            minutePicker.setMaxValue(59);
            minutePicker.setMinValue(0);
            secondPicker.setMaxValue(59);
            secondPicker.setMinValue(0);

            dayPicker.setValue(days);
            hourPicker.setValue(hours);
            minutePicker.setValue(minutes);
            secondPicker.setValue(seconds);

            dayPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    days = newVal;
                }
            });

            hourPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    hours = newVal;
                }
            });

            minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    minutes = newVal;
                }
            });

            secondPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    seconds = newVal;
                }
            });
        }

        return new AlertDialog.Builder(getActivity())
                .setView(v)
                .setTitle(R.string.interval_picker)
                .setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                            }
                        })
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dayPicker.clearFocus();
                                hourPicker.clearFocus();
                                minutePicker.clearFocus();
                                secondPicker.clearFocus();
                                sendResult(Activity.RESULT_OK);
                            }
                        }).create();
    }
}